<template>
  <div class="marketing-analysis">
    <!-- 数据筛选器 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleFilterChange"
          />
        </el-form-item>
        <el-form-item label="活动类型">
          <el-select v-model="filterForm.activityTypes" multiple collapse-tags @change="handleFilterChange">
            <el-option label="全部" value="all" />
            <el-option label="优惠券" value="coupon" />
            <el-option label="折扣活动" value="discount" />
            <el-option label="赠品活动" value="gift" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilterChange">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 营销数据概览 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>活动总数</span>
            </div>
          </template>
          <div class="card-body">
            <div class="amount">{{ formatNumber(marketingData.totalActivities) }}</div>
            <div class="trend">
              <span>进行中活动</span>
              <span class="value">{{ formatNumber(marketingData.activeActivities) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>活动参与人数</span>
            </div>
          </template>
          <div class="card-body">
            <div class="amount">{{ formatNumber(marketingData.totalParticipants) }}</div>
            <div class="trend">
              <span>新增参与</span>
              <span class="value">{{ formatNumber(marketingData.newParticipants) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>活动销售额</span>
            </div>
          </template>
          <div class="card-body">
            <div class="amount">¥{{ formatNumber(marketingData.totalSales) }}</div>
            <div class="trend">
              <span>转化率</span>
              <span class="value">{{ marketingData.conversionRate }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>优惠券发放</span>
            </div>
          </template>
          <div class="card-body">
            <div class="amount">{{ formatNumber(marketingData.totalCoupons) }}</div>
            <div class="trend">
              <span>使用率</span>
              <span class="value">{{ marketingData.couponUsageRate }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 活动列表 -->
    <el-card class="table-card" v-loading="tableLoading">
      <template #header>
        <div class="card-header">
          <span>活动列表</span>
          <el-button type="primary" @click="handleCreateActivity">创建活动</el-button>
        </div>
      </template>
      <el-table :data="activityList" style="width: 100%" border>
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="name" label="活动名称" min-width="180" />
        <el-table-column prop="type" label="活动类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getActivityTypeTag(row.type)">
              {{ getActivityTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="活动状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getActivityStatusTag(row.status)">
              {{ getActivityStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="participants" label="参与人数" width="100" />
        <el-table-column prop="sales" label="销售额" width="120">
          <template #default="{ row }">
            ¥{{ formatNumber(row.sales) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewActivity(row)">查看</el-button>
            <el-button v-if="row.status === 0" link type="primary" @click="handleEditActivity(row)">编辑</el-button>
            <el-button v-if="row.status === 0" link type="danger" @click="handleDeleteActivity(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMarketingStatistics, getMarketingActivities, deleteMarketingActivity } from '@/api/wash_service'

// 营销数据概览
const marketingData = ref({
  totalActivities: 0,
  activeActivities: 0,
  totalParticipants: 0,
  newParticipants: 0,
  totalSales: 0,
  conversionRate: 0,
  totalCoupons: 0,
  couponUsageRate: 0
})

// 活动列表数据
const tableLoading = ref(false)
const activityList = ref([])
const total = ref(0)
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  type: '',
  status: ''
})

// 筛选表单
const filterForm = ref({
  dateRange: [],
  activityTypes: ['all']
})

// 活动类型选项
const activityTypeOptions = [
  { label: '优惠券', value: 'coupon' },
  { label: '折扣活动', value: 'discount' },
  { label: '赠品活动', value: 'gift' }
]

// 活动状态选项
const activityStatusOptions = [
  { label: '未开始', value: 0 },
  { label: '进行中', value: 1 },
  { label: '已结束', value: 2 },
  { label: '已取消', value: 3 }
]

// 格式化数字
const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 获取活动类型标签
const getActivityTypeTag = (type) => {
  const map = {
    coupon: 'success',
    discount: 'warning',
    gift: 'info'
  }
  return map[type] || 'info'
}

// 获取活动类型标签文本
const getActivityTypeLabel = (type) => {
  const item = activityTypeOptions.find(item => item.value === type)
  return item ? item.label : type
}

// 获取活动状态标签
const getActivityStatusTag = (status) => {
  const map = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return map[status] || 'info'
}

// 获取活动状态标签文本
const getActivityStatusLabel = (status) => {
  const item = activityStatusOptions.find(item => item.value === status)
  return item ? item.label : status
}

// 获取营销数据概览
const getMarketingData = async () => {
  try {
    const res = await getMarketingStatistics(filterForm.value)
    if (res && (res.code === 200 || res.data)) {
      const data = res.data || res
      Object.assign(marketingData.value, {
        totalActivities: data.totalActivities || 0,
        activeActivities: data.activeActivities || 0,
        totalParticipants: data.totalParticipants || 0,
        newParticipants: data.newParticipants || 0,
        totalSales: data.totalSales || 0,
        conversionRate: data.conversionRate || 0,
        totalCoupons: data.totalCoupons || 0,
        couponUsageRate: data.couponUsageRate || 0
      })
    }
  } catch (error) {
    console.error('获取营销数据概览失败:', error)
    ElMessage.warning('获取营销数据失败，请检查网络连接')
  }
}

// 获取活动列表
const getActivityList = async () => {
  tableLoading.value = true
  try {
    const res = await getMarketingActivities({
      ...queryParams.value,
      ...filterForm.value
    })
    
    if (res && (res.code === 200 || res.data || res.content)) {
      const data = res.data || res
      activityList.value = data.content || data.records || data || []
      total.value = data.totalElements || data.total || 0
    } else {
      activityList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.warning('获取活动列表失败，请检查网络连接')
    activityList.value = []
    total.value = 0
  } finally {
    tableLoading.value = false
  }
}

// 筛选变化处理
const handleFilterChange = () => {
  queryParams.value.pageNum = 1
  getMarketingData()
  getActivityList()
}

// 重置筛选
const resetFilter = () => {
  filterForm.value = {
    dateRange: [],
    activityTypes: ['all']
  }
  handleFilterChange()
}

// 分页处理
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getActivityList()
}

const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getActivityList()
}

// 创建活动
const handleCreateActivity = () => {
  ElMessage.info('跳转到创建活动页面')
}

// 查看活动
const handleViewActivity = (row) => {
  ElMessage.info(`查看活动: ${row.name}`)
}

// 编辑活动
const handleEditActivity = (row) => {
  ElMessage.info(`编辑活动: ${row.name}`)
}

// 删除活动
const handleDeleteActivity = (row) => {
  ElMessageBox.confirm(
    '确认删除该活动吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteMarketingActivity(row.id)
      if (res && (res.code === 200 || res.success)) {
        ElMessage.success('删除成功')
        getActivityList()
      }
    } catch (error) {
      console.error('删除活动失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 初始化
onMounted(() => {
  getMarketingData()
  getActivityList()
})
</script>

<style scoped>
.marketing-analysis {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.data-overview {
  margin-bottom: 20px;
}

.data-card {
  height: 120px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-body {
  padding: 10px 0;
}

.amount {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}

.trend {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 14px;
}

.value {
  color: #67C23A;
  font-weight: bold;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 